package com.kltn.zigo;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PositionMapActivity  extends FragmentActivity implements OnClickListener,OnMyLocationChangeListener,OnMarkerDragListener, OnMapClickListener {
	// Google Map
    private GoogleMap googleMap;
    private Circle circle;
    private Marker marker;
    private MarkerOptions markeroption;
    private LatLng locationMarker;
    private LocationClient mLocationClient;
    
    private Button btnLocation;
    private Button btnOkLoc;
    private EditText edtAddressSearch;
    String adderess;
    Geocoder geoCoder;
    
    String place_longitude;
    String place_latitude;
    
    //JSONParser jParser = new JSONParser();

	// Progress Dialog
	//private ProgressDialog pDialog;

    //private ArrayList<HashMap<String, String>> data;
    
	//ListView list;
	//EditText inputSearch;
	//PlaceAdapter adapter;
    
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_position_map);
		ActionBar actionBar = getActionBar();		
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#b51d21")));
		btnLocation = (Button) findViewById(R.id.btnLocation);
		btnOkLoc = (Button) findViewById(R.id.btnOkLoc);
		edtAddressSearch = (EditText) findViewById(R.id.edt_AddressSearch);
		
		geoCoder = new Geocoder(this, Locale.getDefault()); 
		//final String map = "http://maps.google.co.in/maps?q=" + edtAddressSearch.getText().toString(); 
		adderess = edtAddressSearch.getText().toString();
		place_longitude = getIntent().getStringExtra("longitude");
		place_latitude = getIntent().getStringExtra("latitude");
		
		try {
            // Loading map
            //initilizeMap();
			if (googleMap == null) {
	            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
	 
	            // check if map is created successfully or not
	            if (googleMap == null) {
	                Toast.makeText(getApplicationContext(),
	                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
	                        .show();
	            }
	            else
	            {
	            	googleMap.setMyLocationEnabled(true);
	            	googleMap.setOnMyLocationChangeListener(this);
	            	googleMap.setOnMapClickListener(this);
	            }
	        }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
		
		btnLocation.setOnClickListener(this);
		btnOkLoc.setOnClickListener(this);		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.near_here, menu);
		return true;
	}

	@SuppressLint("NewApi")
	private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
 
            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
            else
            {
            	googleMap.setMyLocationEnabled(true);
            	googleMap.setOnMyLocationChangeListener(this);
            	googleMap.setOnMapClickListener(this);
            }
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }
    
    /*@Override
    public void onMapLongClick(LatLng point) {
    	googleMap.clear();
    	marker = googleMap.addMarker(new MarkerOptions().position(point)
    													.title(point.toString())
    													.draggable(true)
    													.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    }*/
    
    @Override
    public void onMapClick(LatLng point) {
    	googleMap.clear();
    	marker = googleMap.addMarker(new MarkerOptions().position(point)
    													.title(point.toString())
    													.draggable(true)
    													.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    }
    
    @Override
    public void onMyLocationChange(Location lastKnownLocation) {
	        CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
	                new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
	                        lastKnownLocation.getLongitude())).zoom(15).build());
	        googleMap.moveCamera(myLoc);
	        
	    if(googleMap.getMyLocation() != null){
	        Location loc = googleMap.getMyLocation();
	               
        	MarkerOptions marker = new MarkerOptions().position(new LatLng(loc.getLatitude(), loc.getLongitude()))
        																					.title("Vị trí hiện tại")
        																					.draggable(true);
        	googleMap.addMarker(marker);
        }
        
	    if(!place_latitude.equals("") && !place_longitude.equals(""))
	    {
	    	MarkerOptions marker = new MarkerOptions().position(new LatLng(Double.parseDouble(place_latitude), Double.parseDouble(place_longitude)))
														.title("Vị trí hiện tại")
														.draggable(true)
														.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
	    	Marker mk = googleMap.addMarker(marker);
	    	
	    	LatLngBounds.Builder builder = new LatLngBounds.Builder();
	        builder.include(mk.getPosition());
	        LatLngBounds bounds = builder.build();
	        int padding = 10; // offset from edges of the map in pixels
	        CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
	        googleMap.moveCamera(cu);
	    }
	    
        googleMap.setOnMyLocationChangeListener(null);
    }
    
    private void onCheckLocationClick(LatLng ll)
    {
    	//Toast.makeText(this, "File Clicked: "+o.getName()+ "-" + o.getPath(), Toast.LENGTH_SHORT).show();
    	try{
    	Intent resultData = new Intent();
    	resultData.putExtra("latitude", Double.toString(ll.latitude));
    	resultData.putExtra("longitude", Double.toString(ll.longitude));
    	setResult(Activity.RESULT_OK, resultData);
        //startActivity(resultData);
    	finish();
    	}
    	catch(Exception e)
    	{
    		Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    	}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
			case R.id.btnLocation:
			{
				if(edtAddressSearch.getText().toString().trim().equals(""))
				{
					AlertDialog.Builder alert = new AlertDialog.Builder(this);
			    	alert.setTitle("Chú ý");
			    	alert.setMessage("Bạn chưa nhập địa chỉ cần tìm");

		    	    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    	    	public void onClick(DialogInterface dialog, int whichButton) {
		    	    		
		    	    	}
		    	    });
				}
				else
				{
					try {
				        List<Address> addresses = geoCoder.getFromLocationName(edtAddressSearch.getText().toString(), 5);
				        String temp = edtAddressSearch.getText().toString();
				        
				        if (addresses.size() > 0) {
	
				            Double lat = (double) (addresses.get(0).getLatitude());
				            Double lon = (double) (addresses.get(0).getLongitude());
	
				            Log.d("lat-long", "" + lat + "......." + lon);
				            final LatLng user = new LatLng(lat, lon);
				            /*used marker for show the location */
				           			            
				            googleMap.clear();
				        	marker = googleMap.addMarker(new MarkerOptions().position(user)
				        													.title(user.toString())
				        													.draggable(true)
				        													.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
				            // Move the camera instantly to hamburg with a zoom of 15.
				            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, 15));
	
				            // Zoom in, animating the camera.
				            googleMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
				        }
				    } catch (IOException e) {
				        e.printStackTrace();
				    }
				}
				/*if(googleMap != null)
				{
					markeroption = new MarkerOptions().position(new LatLng(googleMap.getMyLocation().getLatitude()
																						, googleMap.getMyLocation()
																									.getLongitude()))
																									.title("Vị trí hiện tại")
																									.draggable(true);
			        marker = googleMap.addMarker(markeroption);
					double lat = marker.getPosition().latitude;
					double lng = marker.getPosition().longitude;

			        
				}*/
				
				
				
				break;
			}
			
			case R.id.btnOkLoc:
			{
				if(marker != null)
				{
					//onCheckLocationClick(new LatLng(googleMap.getMyLocation().getLatitude(), googleMap.getMyLocation().getLongitude()));
					double lat = marker.getPosition().latitude;
					double lng = marker.getPosition().longitude;
					
					onCheckLocationClick(new LatLng(lat, lng));
				}
				else
				{
					AlertDialog.Builder alert = new AlertDialog.Builder(PositionMapActivity.this);
			    	alert.setTitle("Chú ý");
			    	alert.setMessage("Bạn chưa chọn vị trí");
			    	alert.setPositiveButton("Chọn vị trí",
			    	        new DialogInterface.OnClickListener() {
			    	            public void onClick(DialogInterface dialog, int whichButton) {
			    	            }
			    	        });
			    	alert.setNegativeButton("Thoát",
			    	        new DialogInterface.OnClickListener() {
			    	            public void onClick(DialogInterface dialog, int whichButton) {
			    	            	finish();
			    	            }
			    	        });
			    	alert.show();
				}
				break;
			}
		}
	}

	@Override
	public void onMarkerDrag(Marker marker) {
		// TODO Auto-generated method stub
		//markeroption.title(Double.toString(marker.getPosition().latitude) + " - " +  Double.toString(marker.getPosition().longitude));		
		//marker.setTitle(Double.toString(marker.getPosition().latitude) + " - " +  Double.toString(marker.getPosition().longitude));
		markeroption = new MarkerOptions().position(new LatLng(googleMap.getMyLocation().getLatitude()
				, googleMap.getMyLocation()
							.getLongitude()))
							.title(Double.toString(marker.getPosition().latitude) + " - " 
											+  Double.toString(marker.getPosition().longitude))
							.draggable(true);
		 marker = googleMap.addMarker(markeroption);
	}

	@Override
	public void onMarkerDragEnd(Marker marker) {
		// TODO Auto-generated method stub
		//marker.setTitle(Double.toString(marker.getPosition().latitude) + " - " +  Double.toString(marker.getPosition().longitude));
		markeroption = new MarkerOptions().position(new LatLng(googleMap.getMyLocation().getLatitude()
				, googleMap.getMyLocation()
							.getLongitude()))
							.title(Double.toString(marker.getPosition().latitude) + " - " 
											+  Double.toString(marker.getPosition().longitude))
							.draggable(true);
		 marker = googleMap.addMarker(markeroption);
	}

	@Override
	public void onMarkerDragStart(Marker marker) {
		// TODO Auto-generated method stub
		//markeroption.title(Double.toString(marker.getPosition().latitude) + " - " +  Double.toString(marker.getPosition().longitude));
		//marker.setTitle(Double.toString(marker.getPosition().latitude) + " - " +  Double.toString(marker.getPosition().longitude));
		markeroption = new MarkerOptions().position(new LatLng(googleMap.getMyLocation().getLatitude()
				, googleMap.getMyLocation()
							.getLongitude()))
							.title(Double.toString(marker.getPosition().latitude) + " - " 
											+  Double.toString(marker.getPosition().longitude))
							.draggable(true);
		 marker = googleMap.addMarker(markeroption);
			
	}
    
    /*class LoadPlaceAsync extends AsyncTask<String, String, String>
    {
    	PlaceLoader placeload = new PlaceLoader();
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(NearHereActivity.this);
			pDialog.setMessage("Loading places. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
    	
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
	    	//placeload = new PlaceLoader();
			
			data = placeload.GetPlace();
			return null;
		}
		
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					adapter = new PlaceAdapter(NearHereActivity.this, placeload, data);
					//adapter = new PlaceAdapter(ListPlaceActivity.this, placeload);
			        list.setAdapter(adapter);
				}
			});

		}
    }*/
		
}
